//
//  UserAccountOAuthModel.swift
//  SinaWeiBo
//
//  Created by dengchen on 15/11/11.
//  Copyright © 2015年 name. All rights reserved.
//
import SVProgressHUD
import UIKit

class UserAccountOAuthModel {
    
        
    static let shared = UserAccountOAuthModel()
    
    // MARK: - 应用程序信息
    let redirectUri: String = "http://www.baidu.com"
    private let appKey: String = "3039750094"
    private let appSecret: String   = "4135c13d68b19f633f237b480cd701ac"
    
    
    var userlogin:Bool {
        return Account != nil
    }
    
    let Account = UserAccount.loadAccount()
    
    
    
//    finished:(error:NSError)->()
    func loadAccessToken(code:String,finished: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]

        NetWorkTool.shared.requestData("POST", URLString: urlString, parameters: params, success: { (result) -> Void in
            
            if let dict = result as? [String:AnyObject] {

               let ac = UserAccount(dict: dict)

                self.loadUserInfo(ac, finished: finished)
            }

            
            }) { (error) -> Void in
                
                finished(error: error)

        }
        
    }
    
   private func loadUserInfo(Account:UserAccount,finished:(error:NSError?)->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid" : Account.uid! , "access_token" : Account.access_token!]
    
    
        NetWorkTool.shared.requestData("GET", URLString: urlString, parameters: params, success: { (result) -> Void in
            
            if let dict = result as? [String:AnyObject] {
                
                Account.avatar_large = dict["avatar_large"] as? String
                Account.name = dict["name"] as? String

                Account.saveAccount()
                
                finished(error: nil)
                
            }else {
                SVProgressHUD.showErrorWithStatus("获取用户信息失败")
            }
            
            }) { (error) -> Void in
                
                SVProgressHUD.showErrorWithStatus("获取用户信息失败")
                finished(error: error)
        
            }
    
    
    }
    
    
    func oauthURL() ->NSURL {
        
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(self.redirectUri)"
        
        return NSURL(string: URLString)!
    }
}
